package goose

import (
	"gitee.com/crack007/goose/gscore"
	"github.com/spf13/cobra"
)

// 启动应用。
func Execute(builder gscore.IBuilder) error {
	builder.PreFlags()
	cobraCmd := builder.GetCobraCmd()
	var serverInstance gscore.IServer

	cobraCmd.PreRun = func(cmd *cobra.Command, args []string) {
		var err error
		serverInstance, err = builder.Build()
		if err != nil {
			panic(err)
		}

		serverInstance.InjectHandle(builder.GetHandle())
		serverInstance.OnBeforeInit()
	}

	cobraCmd.Run = func(cobraCmd *cobra.Command, args []string) {
		serverInstance.OnInitConfig()
		serverInstance.OnInitInject()
		serverInstance.OnInitService()
		serverInstance.OnBuild()
		serverInstance.OnInitRouter()
		serverInstance.OnBeforeRun()
		serverInstance.OnRun()
	}

	return cobraCmd.Execute()
}

// 多模块应用
func buildModuleCmd(builder gscore.IBuilder) *cobra.Command {
	cobraCmd := builder.GetCobraCmd()
	builder.PreFlags()
	var serverInstance gscore.IServer

	cobraCmd.PreRun = func(cmd *cobra.Command, args []string) {
		builder.PreFlags()
		var err error
		serverInstance, err = builder.Build()
		if err != nil {
			panic(err)
		}

		serverInstance.InjectHandle(builder.GetHandle())
		serverInstance.OnBeforeInit()
	}

	cobraCmd.Run = func(cobraCmd *cobra.Command, args []string) {
		serverInstance.OnInitConfig()
		serverInstance.OnInitInject()
		serverInstance.OnInitService()
		serverInstance.OnBuild()
		serverInstance.OnInitRouter()
		serverInstance.OnBeforeRun()
		serverInstance.OnRun()
	}

	return cobraCmd
}
